import axios from 'axios'
import type { 
  ApiResponse, 
  ConfigListItem, 
  EquipmentTemplate, 
  SkillConfig, 
  ValidationResult,
  ConfigStats,
  ImportOptions,
  ExportOptions
} from '@/types/config'

// 创建 axios 实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证头等
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    
    // 处理网络错误
    if (!error.response) {
      return Promise.reject({
        success: false,
        message: '网络连接失败，请检查服务器是否正常运行'
      })
    }
    
    // 处理HTTP错误
    const { status, data } = error.response
    return Promise.reject({
      success: false,
      message: data?.message || `请求失败 (${status})`,
      errors: data?.errors
    })
  }
)

export const configApi = {
  // === 配置列表 ===
  async getConfigList(): Promise<ApiResponse<ConfigListItem[]>> {
    return api.get('/configs')
  },

  // === 装备配置 ===
  async getEquipments(): Promise<ApiResponse<EquipmentTemplate[]>> {
    return api.get('/configs/equipments')
  },

  async saveEquipments(equipments: EquipmentTemplate[]): Promise<ApiResponse> {
    return api.post('/configs/equipments', { equipments })
  },

  async getEquipment(id: string): Promise<ApiResponse<EquipmentTemplate>> {
    return api.get(`/configs/equipments/${id}`)
  },

  async saveEquipment(equipment: EquipmentTemplate): Promise<ApiResponse> {
    return api.put(`/configs/equipments/${equipment.id}`, equipment)
  },

  async deleteEquipment(id: string): Promise<ApiResponse> {
    return api.delete(`/configs/equipments/${id}`)
  },

  // === 技能配置 ===
  async getSkills(): Promise<ApiResponse<SkillConfig[]>> {
    return api.get('/configs/skills')
  },

  async saveSkills(skills: SkillConfig[]): Promise<ApiResponse> {
    return api.post('/configs/skills', { skills })
  },

  async getSkill(id: string): Promise<ApiResponse<SkillConfig>> {
    return api.get(`/configs/skills/${id}`)
  },

  async saveSkill(skill: SkillConfig): Promise<ApiResponse> {
    return api.put(`/configs/skills/${skill.skillId}`, skill)
  },

  async deleteSkill(id: string): Promise<ApiResponse> {
    return api.delete(`/configs/skills/${id}`)
  },

  // === 验证 ===
  async validateConfigs(type?: string): Promise<ApiResponse<ValidationResult | Record<string, ValidationResult>>> {
    const url = type ? `/validation/${type}` : '/validation'
    return api.get(url)
  },

  async validateEquipment(equipment: EquipmentTemplate): Promise<ApiResponse<ValidationResult>> {
    return api.post('/validation/equipment', equipment)
  },

  async validateSkill(skill: SkillConfig): Promise<ApiResponse<ValidationResult>> {
    return api.post('/validation/skill', skill)
  },

  // === 统计信息 ===
  async getStats(): Promise<ApiResponse<ConfigStats>> {
    return api.get('/stats')
  },

  // === 配置管理 ===
  async reloadConfigs(): Promise<ApiResponse> {
    return api.post('/configs/reload')
  },

  async resetConfigs(type: string): Promise<ApiResponse> {
    return api.post(`/configs/reset/${type}`)
  },

  async backupConfigs(): Promise<ApiResponse<{ backupId: string, filename: string }>> {
    return api.post('/configs/backup')
  },

  async restoreConfigs(backupId: string): Promise<ApiResponse> {
    return api.post(`/configs/restore/${backupId}`)
  },

  // === 导入导出 ===
  async importConfigs(file: File, options: ImportOptions): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('options', JSON.stringify(options))

    return api.post('/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  async exportConfigs(options: ExportOptions): Promise<ApiResponse<{ filename: string, downloadUrl: string }>> {
    return api.post('/export', options)
  },

  async downloadExport(filename: string): Promise<Blob> {
    const response = await api.get(`/export/download/${filename}`, {
      responseType: 'blob'
    })
    return response as any
  },

  // === 模板和预设 ===
  async getEquipmentTemplates(): Promise<ApiResponse<EquipmentTemplate[]>> {
    return api.get('/templates/equipments')
  },

  async getSkillTemplates(): Promise<ApiResponse<SkillConfig[]>> {
    return api.get('/templates/skills')
  },

  async saveTemplate(type: 'equipment' | 'skill', template: EquipmentTemplate | SkillConfig): Promise<ApiResponse> {
    return api.post(`/templates/${type}`, template)
  },

  // === 搜索 ===
  async searchConfigs(query: string, type?: string): Promise<ApiResponse<Array<EquipmentTemplate | SkillConfig>>> {
    return api.get('/search', {
      params: { q: query, type }
    })
  },

  // === 版本管理 ===
  async getConfigHistory(type: string, id: string): Promise<ApiResponse<Array<{ version: string, timestamp: number, changes: string[] }>>> {
    return api.get(`/history/${type}/${id}`)
  },

  async revertConfig(type: string, id: string, version: string): Promise<ApiResponse> {
    return api.post(`/history/${type}/${id}/revert/${version}`)
  },

  // === 服务器状态 ===
  async ping(): Promise<ApiResponse<{ status: string, timestamp: number }>> {
    return api.get('/ping')
  },

  async getServerInfo(): Promise<ApiResponse<{ 
    version: string
    uptime: number
    memory: { used: string, total: string }
    configs: { loaded: number, lastUpdate: number }
  }>> {
    return api.get('/server-info')
  }
}

// 导出用于测试的 api 实例
export { api }
